import { useEffect, useState } from 'react'
import {
    Form,
    Input,
    Button,
    Switch,
    Toast,
} from 'antd-mobile'

import styles from '@/assets/css/login.module.less'
import { encode } from 'js-base64';
import http from '../helper/http';
import { useNavigate } from 'react-router-dom';
import { FormItem } from 'antd-mobile/es/components/form/form-item';
export default () => {
    const [checkCodeUrl, setCheckCodeUrl] = useState('/api/checkcode');
    const [checkedRememberPwd, setCheckedRememberPwd] = useState(true);
    const defaultThemeChecked = localStorage.getItem('color-scheme') === 'dark';

    const navigate = useNavigate();

    const gotoHome = () => {
        navigate('/home/mywork')
    }

    // 登录验证
    const checkLogined = () => {
        http.get('/user', { data: {} }).then(res => {
            const userinfo = res.data.userinfo;
            const flag = userinfo.length > 0;
            if (flag) {
                localStorage.setItem('username', userinfo[0].username)
                gotoHome();
            } else {
                localStorage.removeItem('username')
            }
        })
    }

    useEffect(() => {
        const scheme = localStorage.getItem('color-scheme') ?? 'light'
        document.documentElement.setAttribute('data-prefers-color-scheme', scheme)
        checkLogined()
    }, [])

    const onCheckCodeClick = () => {
        const url = '/api/checkcode?t=' + new Date().getTime()
        setCheckCodeUrl(url)
    }

    const themeChange = (dark: boolean) => {
        localStorage.setItem('color-scheme', dark ? 'dark' : 'light');
        if (dark) {
            document.documentElement.setAttribute(
                'data-prefers-color-scheme',
                'dark'
            )
        } else {
            document.documentElement.setAttribute(
                'data-prefers-color-scheme',
                'light'
            )
        }
    }

    const initFormValue = () => {
        return {
            username: localStorage.getItem('login-username') ?? '',
            password: localStorage.getItem('login-password') ?? ''
        }
    }
    const onFinish = (values: any) => {
        const siteform = {
            newusertype: '1',
            wxUnionid: '',
            loginarea: '',
            usercode: values.username,
            PASS_HASH: encode(values.password),
            YZM: values.validcode,
        };
        http.post('/login', { data: siteform }).then(res => {
            if (res.data === null) {
                Toast.show({
                    content: '登录成功',
                    afterClose: () => {
                        // 跳转到首页
                        checkLogined();
                    }
                })

                if (checkedRememberPwd) {
                    localStorage.setItem('login-username', values.username);
                    localStorage.setItem('login-password', values.password);
                } else {
                    localStorage.setItem('login-username', '');
                    localStorage.setItem('login-password', '');
                }

                return;
            }
            const data = res.data;
            if (!data.flag) {
                Toast.show({
                    icon: 'fail',
                    content: data.msg,
                })
                onCheckCodeClick();
            }
        })
    }

    return (
        <div className={styles.login}>

            <Form
                layout='horizontal'
                onFinish={onFinish}
                initialValues={initFormValue()}
                footer={
                    <Button block type='submit' color='primary'>
                        登录
                    </Button>
                }
            >
                <Form.Header>
                    <div className={styles.loginheader}>
                        <img src='https://www.hspcn.com/Content/themes/login_bg/logo2_index_tt.png'></img>
                        <h5>工作量查询助手</h5>
                    </div>

                </Form.Header>
                <Form.Item
                    name='username'
                    label='手机号码'
                    rules={[{ required: true, message: '手机号码不能为空' }]}
                >
                    <Input placeholder='请输入手机号码' />
                </Form.Item>
                <Form.Item name='password' label='登录密码'
                    rules={[{ required: true, message: '登录密码不能为空' }]}>
                    <Input type='password' placeholder='请输入登录密码'
                    />
                </Form.Item>

                <Form.Item name='validcode' label='验证码'
                    rules={[{ required: true, message: '验证码不能为空' }]}
                    extra={<img onClick={onCheckCodeClick} src={checkCodeUrl} ></img>}
                >
                    <Input type='number' placeholder='请输入验证码'
                    />
                </Form.Item>

                <FormItem name='remember' label='记住密码'>
                    <Switch checked={checkedRememberPwd} onChange={setCheckedRememberPwd} />
                </FormItem>
            </Form>

            <div className={styles.theme}>
                <Switch onChange={themeChange} defaultChecked={defaultThemeChecked} checkedText='深色模式' uncheckedText='浅色模式'></Switch>
            </div>

        </div>
    )
}